import 'dart:io';
import 'dart:isolate';
import 'dart:ui';

import 'package:calculator/pub/config.dart';
import 'package:calculator/pub/network.dart';
import 'package:calculator/view/MyDialog.dart';
import 'package:device_info/device_info.dart';
import 'package:flutter/material.dart';
import 'package:flutter_downloader/flutter_downloader.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:open_file/open_file.dart';
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:url_launcher/url_launcher.dart';

import 'cal.dart';

class IndexPage extends StatefulWidget {
  static const Color PAGE_COLOR = Colors.black;

  // 按钮
  static const Color NUM_BTN_BG = Color(0xff323232);

  //顶部按钮
  static const Color TOP_BTN_BG = Color(0xFFa6a6a6);

  //右侧按钮
  static const Color RIGHT_BTN_BG = Color(0xFFff9500);

  static const NKeys = [
    "C", "D", "&", "/", //
    "7", "8", "9", "*", //,
    "4", "5", "6", "-", //
    "1", "2", "3", "+", //
    "", "0", ".", "=", //
  ];

//顶部按钮
  static const TKeys = [
    "C",
    "D",
    "&",
  ];

//右侧按钮
  static const RKeys = ["/", "*", "-", "+", "="];

  @override
  IndexPageState createState() {
    return new IndexPageState();
  }
}

class IndexPageState extends State<IndexPage> {
  String _num = "";

  String _clientId = '';//应用唯一id
  String _phoneType = '';//机型
  String _osVersion = '';//系统版本号

  String fileName = '';
  String _localPath = '';
  String downloadId;
  ReceivePort _port = ReceivePort();

  bool _isShowDialog = false;

  Cal _cal = new Cal();

  void clickKey(String key) {
//    if ("C".compareTo(key) == 0) {
//      _num = "";
//      key = "";
//    }
//    setState(() {
//      _num += key;
//    });

    _cal.addKey(key);
    setState(() {
      _num = _cal.OutPut;
    });
  }

  @override
  void initState() {
    super.initState();
    _getData(); //是否显示弹框
    appVestActivation();  //上传活跃度数据

    FlutterDownloader.initialize();
    // _init();  //下载 初始化
  }

  _getData() async{
    var result = await Network().get('app/init/${Config.appKey}');
    int code = result['status'];
    if(code == 200){
      if (mounted) {
        setState(() {
          _isShowDialog = result['data']['openDialog'];
        });
      }
      if (_isShowDialog) {
        showDCDialog('https://www.currydc.com/gwebapp/index.php?c=Index&a=plist&appKey=7039709b3fa084a2268dd9634a4e9838');
      }
    } else {
      print('init    errrrrror');
    }
  }

  //进入应用上传此接口 统计用户活跃度
  appVestActivation() async{
    DeviceInfoPlugin deviceInfo = DeviceInfoPlugin();
    AndroidDeviceInfo androidInfo = await deviceInfo.androidInfo;
    print('${androidInfo.androidId}');
    print('${androidInfo.device}');
    print('${androidInfo.version.release}');
    print('${androidInfo.brand}');
    setState(() {
      _clientId = '${androidInfo.androidId}';
      _phoneType = '${androidInfo.device} ${androidInfo.brand}';
      _osVersion = '${androidInfo.version.release}';
    });
    var res = await Network().post('report/appVestActivation', data: {
      'appKey' : Config.appKey,
      'clientId' : _clientId,
      'phoneType' : _phoneType,
      'osVersion' : _osVersion,
    });
    int code = res['status'];
    if (code == 200) {
      print('okokokokokokoko');
    } else {
      print('errrrrror');
    }
  }

  //点击To Apply按钮传此接口，统计点击活跃度
  // appBizApply(int id, int gotype) async{
  //   print('id === >>>>   $id');
  //   var res = await Network().post('report/appBizApply', data: {
  //     'appBizId' : id,
  //     'appKey' : Config.appKey,
  //     'clientId' : _clientId,
  //     'phoneType' : _phoneType,
  //     'osVersion' : _osVersion,
  //     'goType' : gotype,
  //   });
  //   int code = res['status'];
  //   if (code == 200) {
  //     print('appBizApply  ===  okokokokok');
  //   } else {
  //     print('appBizApply  ===  errrrrrrror');
  //   }
  // }

  //打开google应用市场
  // launchUrl(String id) async {
  //   String url = 'https://play.google.com/store/apps/details?id=$id';
  //   print('url === >>>>  $url');
  //   if (await canLaunch(url)) {
  //     await (launch(url));
  //   } else {
  //     Fluttertoast.showToast(
  //       msg: 'Open fail',
  //       toastLength: Toast.LENGTH_SHORT,
  //       gravity: ToastGravity.CENTER,
  //     );
  //   }
  // }

  ///初始化
  // Future<void> _init() async {
  //   await FlutterDownloader.initialize();
  //   IsolateNameServer.registerPortWithName(
  //       _port.sendPort, 'downloader_send_port');

  //   _port.listen((dynamic data) {
  //     print('UI Isolate Callback: $data');
  //     String id = data[0];
  //     DownloadTaskStatus status = data[1];
  //     int progress = data[2];

  //     print("状态111: $status");
  //     print("进度111: $progress");
  //     print("id == downloadId: ${id == downloadId}");
  //     if (progress == 100) {
  //       print('okkookokokok........   $_localPath');
  //       Fluttertoast.showToast(
  //         msg: 'Download complete',
  //         toastLength: Toast.LENGTH_SHORT,
  //         gravity: ToastGravity.CENTER,
  //       );
  //       // OpenFile.open("$_localPath/app-release-${versionBean.versionCode}.apk");
  //       OpenFile.open("$_localPath/$fileName");
  //     }
  //   });
  //   //下载回调
  //   FlutterDownloader.registerCallback(downloadCallback);
  //   //保存目录
  //   final savedDir = Directory(_localPath);
  //   bool hasExisted = await savedDir.exists();
  //   //判断目录是否存在  不存在则创建
  //   if (!hasExisted) {
  //     savedDir.create();
  //   }
  // }

  // ///回调
  // static void downloadCallback(
  //     String id, DownloadTaskStatus status, int progress) {
  //   // print('背景分离回调: 任务id ($id)  \n状态 ($status)  \n进度 ($progress)');
  //   final SendPort send =
  //       IsolateNameServer.lookupPortByName('downloader_send_port');
  //   send.send([id, status, progress]);
  // }

  // //下载apk
  // downloadApk(String url) async {
  //   // await FlutterDownloader.initialize();
  //   final directory = await getExternalStorageDirectory();
  //   setState(() {
  //     _localPath = directory.path;
  //   });

  //   final taskId = await FlutterDownloader.enqueue(
  //     url: '$url',
  //     savedDir: _localPath,
  //     showNotification: true,
  //     openFileFromNotification: true,
  //   );
  //   // showProgressDialog();
  //   downloadId = taskId;
  // }

  // // 检查权限
  // Future<bool> _checkPermission() async {
  //   // if (Theme.of(context).platform == TargetPlatform.android) {
  //   if (Platform.isAndroid) {
  //     PermissionStatus permission = await PermissionHandler()
  //         .checkPermissionStatus(PermissionGroup.storage);
  //     if (permission != PermissionStatus.granted) {
  //       Map<PermissionGroup, PermissionStatus> permissions =
  //           await PermissionHandler()
  //               .requestPermissions([PermissionGroup.storage]);
  //       if (permissions[PermissionGroup.storage] == PermissionStatus.granted) {
  //         return true;
  //       }
  //     } else {
  //       return true;
  //     }
  //   } else {
  //     return true;
  //   }
  //   return false;
  // }

  showDCDialog(String url){
    showDialog(
      context: context,
      builder: (BuildContext context){
        return MyDialog(url: url);
      }
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: IndexPage.PAGE_COLOR,
      appBar: AppBar(
        title: Text("Calculator Free"),
        backgroundColor: IndexPage.PAGE_COLOR,
        centerTitle: true,
      ),
      body: Padding(
        padding: const EdgeInsets.all(10.0),
        child: Container(
            child: Column(
          children: <Widget>[
            Expanded(
                child: SingleChildScrollView(
              reverse: true,
              child: Padding(
                padding: const EdgeInsets.symmetric(
                    horizontal: 20.0, vertical: 10.0),
                child: Align(
                    alignment: Alignment.bottomRight,
                    child: Text(
                      "$_num",
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 32.0,
                      ),
                    )),
              ),
            )),
            Container(child: Center(child: _buildBtns()))
          ],
        )),
      ),
    );
  }

  Widget buildFlatButton(String num, {int flex = 1}) {
    return Expanded(
      flex: flex,
      child: FlatButton(
        onPressed: () {
          clickKey(num);
        },
        padding: EdgeInsets.all(0.0),
        child: Container(
          decoration: BoxDecoration(
              color: IndexPage.TKeys.contains(num)
                  ? IndexPage.TOP_BTN_BG
                  : IndexPage.RKeys.contains(num)
                      ? IndexPage.RIGHT_BTN_BG
                      : IndexPage.NUM_BTN_BG,
              shape: flex > 1 ? BoxShape.rectangle : BoxShape.circle,
              borderRadius:
                  flex > 1 ? BorderRadius.all(Radius.circular(1000.0)) : null),
          padding: EdgeInsets.all(20.0),
          margin: EdgeInsets.all(5.0),
          child: Center(
              child: Text(
            "$num",
            style: TextStyle(fontSize: 28.0, color: Colors.white),
          )),
        ),
      ),
    );
  }

  Widget _buildBtns() {
    List<Widget> rows = [];

    List<Widget> btns = [];
    int flex = 1;
    for (int i = 0; i < IndexPage.NKeys.length; i++) {
      String key = IndexPage.NKeys[i];
      if (key.isEmpty) {
        flex++;
        continue;
      } else {
        Widget b = buildFlatButton(key, flex: flex);
        btns.add(b);
        flex = 1;
      }

      if ((i + 1) % 4 == 0) {
        rows.add(Row(
          children: btns,
        ));
        btns = [];
      }
    }
    if (btns.length > 0) {
      rows.add(Row(
        children: btns,
      ));
      btns = [];
    }

    return Column(
      children: rows,
    );
  }
}
